<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <select id="province">
        <option>===请输入省份===</option>
    </select>
    <select id="city">
        <option>===请输入城市===</option>
    </select>
    <script>
        // 准备数据
      var data = [
        {"code" : "0001", "name" : "广东省",
            "cities" : [
                {"code" : "00010001", "name" : "广州市"},
                {"code" : "00010002", "name" : "深圳市"},
                {"code" : "00010003", "name" : "东莞市"}
            ]
        },
        {"code" : "0002", "name" : "湖南省",
            "cities" : [
                {"code" : "00020001", "name" : "长沙市"},
                {"code" : "00020002", "name" : "衡阳市"},
                {"code" : "00020003", "name" : "郴州市"}
            ]
        },
        {"code" : "0003", "name" : "江西省",
            "cities" : [
                {"code" : "00030001", "name" : "南昌市"},
                {"code" : "00030002", "name" : "赣州市"},
                {"code" : "00030003", "name" : "吉安市"}
            ]
        }
    ];
    window.onload = function(){
        //获取省份
        var province = document.getElementById('province');
        //循环data数据
        for(var i = 0; i < data.length;i++){
            // 把data中的数据给json
            var json = data[i];
            // new Option("文本","值",true,true).后面两个true分别表示默认被选中和有效!
            var option = new Option(json.name,json.code,false,false);
            province.add(option);
        }

        // 当省份发生改变
        province.onchange = function(){
            // 获取城市
            var city = document.getElementById('city');

            //循环清空city里面数据（由于第一条数据不能清空，因此使用i--）
            for(var i = city.length-1;i>0;i--){
                city.remove(i);
            }

            //循环data数据
            for(var i = 0 ; i < data.length ;i++){
                // 把data中的数据给json
                 var json = data[i];
                //  如果json中的code码和当前选中的这个code相等时
                 if(json.code == this.value){
                    //   循环data数据
                    for(var j = 0 ; j < data.length; j++){
                        // 把data中的城市中的所有信息给cities
                        var cities = json.cities[j];
                        var option = new Option(cities.name,cities.code,false,false);
                        city.add(option);
                    }
                 }
            }
        }
    }
    </script>
</body>
</html>
